package com.ciwong.mobilelib.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Chronometer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义倒计时
 *
 * @author res-qqlin
 * @version ciwong v.2.0 2015/7/31
 * @since ciwong v.2.0
 */
public class CountDownTimer extends Chronometer
{
    private long mTime;

    private long mNextTime;

    private OnTimeCompleteListener mListener;

    private SimpleDateFormat mTimeFormat;

    public CountDownTimer(Context context)
    {
        super(context);

    }

    public CountDownTimer(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        mTimeFormat = new SimpleDateFormat("mm:ss");
        this.setOnChronometerTickListener(listener);
    }

    // 重新启动计时
    public void reStart(long times)
    {
        if (times == -1)
        {
            mNextTime = mTime;
        }
        else
        {
            mTime = mNextTime = times;
        }
        this.start();
    }

    public void reStart()
    {
        reStart(-1);
    }

    // 不建议方法名用onResume()或onPause()，容易和activity生命周期混淆
    // 继续计时
    public void timerResume()
    {
        this.start();
    }

    // 暂停计时
    public void timerPause()
    {
        this.stop();
    }

    /**
     * 设置时间格式
     *
     * @param pattern
     *            计时格式
     */
    public void setTimeFormat(String pattern)
    {
        mTimeFormat = new SimpleDateFormat(pattern);
    }

    public void setOnTimeCompleteListener(OnTimeCompleteListener l)
    {
        mListener = l;
    }

    OnChronometerTickListener listener = new OnChronometerTickListener()
    {
        @Override
        public void onChronometerTick(Chronometer chronometer)
        {
            if (mNextTime <= 0)
            {
                if (mNextTime == 0)
                {
                    CountDownTimer.this.stop();
                    if (null != mListener)
                        mListener.onTimeComplete();
                }
                mNextTime = 0;
                updateTimeText();
                return;
            }

            mNextTime--;

            updateTimeText();
        }
    };

    // 初始化时间(秒)
    public void initTime(long times)
    {
        mTime = mNextTime = times;
        updateTimeText();
    }

    // 初始化时间（分秒）
    public void initTime(long timem, long times)
    {
        initTime(timem * 60 + times);
    }

    private void updateTimeText()
    {
        this.setText(mTimeFormat.format(new Date(mNextTime * 1000)));
    }

    interface OnTimeCompleteListener
    {
        void onTimeComplete();
    }

}
